package dse.messages.singleversion;

import dse.DataObject;
import dse.Experiment;
import dse.ExperimentRecorder;
import dse.messages.Message;
import dse.messages.MessageHandler;
import dse.messages.MessageSender;
import dse.messages.MessageType;

public class UpdateConfirmMessageHandler extends MessageSender implements
		MessageHandler {

	private DataObject dobj;
	private int shareIndex;
	private ShareDownloader shareDownloader;
	private boolean affirmative;
	
	public UpdateConfirmMessageHandler (
			Experiment experiment, 
			DataObject dobj, 
			int shareIndex,
			boolean affirm,
			ShareDownloader shareDownloader
			)
	{
		super(experiment);
		
		this.dobj = dobj;
		this.shareIndex = shareIndex;
		this.affirmative = affirm;
		this.shareDownloader = shareDownloader;
	}
		
	public boolean acceptMessage (
			Message message
			)
	{
		return !shareDownloader.isDoneUpdatingShares();			
	}
	
	public void messageReceived (
			ExperimentRecorder recorder, 
			Message message,
			double timeLeft
			)
	{
		recorder.debug(this, "msgRcvd: " + message, timeLeft);
		// All this really has to do is inform the share downloader that the
		// download has finished.
		if (message.messageType() != MessageType.UpdateConfirm) {
			recorder.warn(
					"UpdateConfirmMessageHandler recieved " + 
					message.messageType() + " message."
					);
			return;
		}
		//message.to().setSequence(Math.max(message.to().getSequence()+1, message.from().getSequence()));
		if(this.affirmative)
			shareDownloader.shareUpdated(
					recorder,
					message.from(),
					dobj, 
					shareIndex, 
					timeLeft
					);
		else
			shareDownloader.shareUpdateFailed(recorder, dobj, shareIndex, timeLeft);
	}
	
	public void messageInterupted (
			ExperimentRecorder recorder, 
			Message message,
			double timeLeft
			)
	{
		recorder.debug(this, "msgIntrpt: " + message, timeLeft);
		
		shareDownloader.shareUpdateFailed(recorder, dobj, shareIndex, timeLeft);
	}

}
